package com.cuz.daileetcode.bat100;

public class 超级洗衣机问题 {

    public static void main(String[] args) {
        int[] ints = {0, 3, 0};
        System.out.println(solution1(ints));
    }

    public static int solution1(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return 0;
        }
        int sum = sum(arr);
        if (sum % arr.length != 0) {
            return -1;
        }
        int avg = sum / arr.length;
        int ans = 0;
        int pre = 0;
        for (int index = 0; index < arr.length; index++) {
            //左边多余的衣服 左边衣服数量-左边洗衣机*平均
            int leftRest = pre - index * avg;
            //  右边多的衣服=>  总数-左边的-当前位置的=右边总和 -
            //           （洗衣机总数-当前位置-1=右边洗衣机数量） * 平均
            int rightRest = (sum - pre - arr[index])
                    - (arr.length - index - 1) * avg;
            int curLoopNeedCount;
            if (leftRest < 0 && rightRest < 0) {
                curLoopNeedCount = (-leftRest) + (-rightRest);
            } else {
                curLoopNeedCount = Math.max(leftRest, rightRest);
            }
            pre += arr[index];
            ans = Math.max(ans, curLoopNeedCount);
        }
        return ans;
    }

    private static int sum(int[] arr) {
        int sum = 0;
        for (int i : arr) {
            sum += i;
        }
        return sum;
    }
}
